﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace GuanYijia.Application
{
    public class RSAHelper
    {
        private string publicKey;
        private string privateKey;

        public RSAHelper(string publicKey, string privateKey)
        {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public string Encrypt(string plainText)
        {
            try
            {
                var publicKeyBytes = Convert.FromBase64String(publicKey);
                using (var rsa = RSA.Create())
                {
                    rsa.ImportSubjectPublicKeyInfo(publicKeyBytes, out _);
                    var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
                    var cipherTextBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.Pkcs1);
                    return Convert.ToBase64String(cipherTextBytes);
                }
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine($"加密失败: {ex.Message}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
                throw;
            }
        }

        public string Decrypt(string cipherText)
        {
            try
            {
                var privateKeyBytes = Convert.FromBase64String(privateKey);
                using (var rsa = RSA.Create())
                {
                    rsa.ImportPkcs8PrivateKey(privateKeyBytes, out _);
                    var cipherBytes = Convert.FromBase64String(cipherText);
                    var plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
                    return Encoding.UTF8.GetString(plainTextBytes);
                }
            }
            catch (CryptographicException ex)
            {
                Console.WriteLine($"解密失败: {ex.Message}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
                throw;
            }
        }

    }
}
